package com.tplhk.retry;


import com.tplhk.retry.retry.RetryUtils;
import com.tplhk.retry.service.impl.EmailSendService;
import com.tplhk.retry.service.impl.SmsSendService;
import com.tplhk.retry.util.AppException;
import com.tplhk.retry.vo.SmsMessageBean;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.support.RetryTemplate;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;


@Slf4j
@SpringBootTest(classes = RetryApplication.class)
public class RetryDemo {

    @Autowired
    SmsSendService smsSendService;

    @Autowired
    EmailSendService emailSendService;

    @Test
    public void testSmsRery(){
        SmsMessageBean smsMessageBean = new SmsMessageBean();
        smsSendService.send(smsMessageBean);
    }

    @Test
    public void testSmsReryByRetryUtils()  {
        SmsMessageBean smsMessageBean = new SmsMessageBean();
        RetryTemplate defaultRetryTemplate = RetryUtils.DEFAULT_RETRY_TEMPLATE;
        try {
            SmsMessageBean retryingToSendSmsMessage = defaultRetryTemplate.execute((RetryCallback<SmsMessageBean, Throwable>) retryContext -> {
                if (retryContext.getRetryCount() > 1) {
                    log.warn("The Msg[{}] is send for the {} times. The Last failure was caused by {}.",
                            smsMessageBean.key(), retryContext.getRetryCount(), retryContext.getLastThrowable().getMessage());
                }

                Object message = smsSendService.doSend(smsMessageBean);

                if (Objects.isNull(message)) {
                    throw new AppException("Failed to send MSG[" + smsMessageBean.key() + "]!");
                }
                return smsMessageBean;

            }, retryContext -> {
                log.info("完蛋了，重试都失败了");
                log.error("Failed to send MSG[{}] after {} retries!", smsMessageBean.key(), retryContext.getRetryCount());
                return null;
            });
            log.info("The Msg[{}] is send successfully.", retryingToSendSmsMessage.key());
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }

    }



    @Test
    public void testEmailRery(){
        SmsMessageBean smsMessageBean = new SmsMessageBean();
        emailSendService.send(smsMessageBean);
    }

}
